﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Coolzon.Common.Config
{
    /// <summary>
    /// 从json文件读取成对象
    /// </summary>
    public static class JsonConfigUtil
    {
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="filepath"></param>
        /// <returns></returns>
        /// <exception cref="System.Exception"></exception>
        public static T LoadFromFile<T>(string filepath) where T : class
        {
            JsonSerializer serializer = new JsonSerializer();
            using (StringReader sr = new StringReader(System.IO.File.ReadAllText(filepath)))
            {
                object o = serializer.Deserialize(new JsonTextReader(sr), typeof(T));
                T t = o as T;
                return t;
            }
        }

        public static T LoadFromString<T>(string content) where T : class
        {
            JsonSerializer serializer = new JsonSerializer();
            using (StringReader sr = new StringReader(content))
            {
                object o = serializer.Deserialize(new JsonTextReader(sr), typeof(T));
                T t = o as T;
                return t;
            }
        }
    }
}
